"""
伯努利实验【只有两种可能结果的实验】
P(X=k) = (n~k)p^k * (1 - p)^n-k
"""


class BernoulliTrail:
    def __init__(self, top_cnt: int, positive_probability: float, target_cnt: int):
        self.top_cnt = top_cnt
        self.positive_probability = positive_probability
        self.target_cnt = target_cnt

    def calculate_probability(self) -> float:
        if self.target_cnt > self.top_cnt:
            raise ValueError("Target count can not be greater than Top count！")
        rate = 0.0
        # 计算反向概率
        reversed_b = 1 - self.positive_probability
        for i in range(0, self.target_cnt + 1):
            ri = (self.positive_probability ** i) * (reversed_b ** (self.target_cnt - i))
            print(f"In No.{i} cycle, P(X={i})={ri:.06f}")
            rate += ri
        return rate


"""
假设某个广告展现后被点击的概率是0.25，那么该广告3次展现，被点击次数少于2次的概率是（）
"""
instance = BernoulliTrail(3, 0.25, 2)
r = instance.calculate_probability()
print(f"Target Result is {r:.06f}")
